package com.smartwork.common.mobile.web;


import com.alibaba.fastjson.JSON;
import com.smartwork.common.mobile.constant.ResponseCodeConst;
import com.smartwork.common.mobile.exception.BizException;
import com.smartwork.common.mobile.vo.BaseRequestData;
import com.smartwork.common.mobile.vo.BaseResponseData;
import com.smartwork.common.persistence.Page;
import com.smartwork.common.utils.StringUtils;
import com.smartwork.modules.sys.entity.User;
import com.smartwork.modules.sys.service.SystemService;
import com.smartwork.modules.sys.utils.LogUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 服务基础类
 *
 * @author albert yan
 */
public class BaseController {

    public static final String CODE = "code";

    public static final String ST = "st";

    public static final String MESSAGE = "message";

    public static final String DETAIL = "detail";

    @Autowired
    private SystemService systemService;


    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());


    protected Map<String, Object> responseMap = new HashMap<String, Object>();


    public BaseController() {
    }

    /**
     * 取得request对象
     *
     * @return
     */
    protected HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    /**
     * 用于处理异常的
     *
     * @return
     */
    @ExceptionHandler({Exception.class})
    protected
    @ResponseBody
    Map<String, Object> bindException(HttpServletRequest request,
                                      HttpServletResponse response, Object handler, Exception ex) {
        LogUtils.saveLog(request, handler, ex, null);
        responseMap = new HashMap<String, Object>();
        logger.error(ex.getMessage());
        if (ex instanceof BizException) {
            responseMap.put(CODE, ((BizException) ex).getCode());
            responseMap.put(MESSAGE, ex.getMessage());
        } else {
            responseMap.put(CODE, ResponseCodeConst.ERROR_SYS);
            responseMap.put(MESSAGE, ex.toString());
        }
        return responseMap;
    }

    /**
     * 正常返回时，共通参数
     */
    protected void setSuccResponseMap() {
        responseMap.put(CODE, ResponseCodeConst.SUCCESS);
        responseMap.put(ST, System.currentTimeMillis());
    }

    /**
     * wj 2015/12/03
     *
     * @param requestData
     * @return 解析请求中包含的String型数据为对象型数据
     * requestData 请求数据对象
     * classType 转换为的指定类型
     * isArray   是否转换成list
     */
    protected Object parserRequestData(BaseRequestData requestData, Class classType, boolean isArray) {
        Object obj = null;
        if (null != requestData && !"".equals(requestData.getBody())) {
            //得到请求参数的文本形式
            String body = requestData.getBody();
            logger.debug("请求数据json格式==================="+body);
            if (isArray) {
                //请求参数如果是数组调用 parseArray转换
                if (null != classType) {
                    obj = JSON.parseArray(body, classType);
                } else {
                    obj = JSON.parseArray(body);
                }
            } else {
                //请求参数如果是对象调用parseObject转换
                if (null != classType) {
                    obj = JSON.parseObject(body, classType);
                } else {
                    obj = JSON.parseObject(body);
                }
            }
        }
        return obj;
    }

    /**
     * 通过请求参数中包含的分页对象数据，封装分页对象
     * wj 2015/12/08
     *
     * @param requestData
     * @return
     */
    protected Page getPage(BaseRequestData requestData) {
        Page page = new Page();
        if (null != requestData) {
            page.setPageNo(requestData.getPage());
            if (null != requestData.getPageSize()) {
                page.setPageSize(requestData.getPageSize());
            } else {
                page.setPageSize(20);
            }
            if (null != requestData.getOrderBy()) {
                page.setOrderBy(requestData.getOrderBy());
            } else {
                page.setOrderBy("");
            }
        }
        return page;
    }

    /**
     * wj 2015/12/07
     * 组装响应信息
     */
    protected BaseResponseData sendResponseData(Integer code,String message, String protocol, Object object) {
        BaseResponseData responseData = new BaseResponseData();
        responseData.setCode(code);
        responseData.setSt(new Date().getTime());
        responseData.setMessage(message);
        responseData.setProtocol(protocol);
        responseData.setData(object);
        return responseData;
    }

    /**
     * 通过请求数据获取当前登录用户
     * wj 2015/12/08
     *
     * @param requestData
     * @return
     */
    protected User getCurrentUser(BaseRequestData requestData) {
        User user = null;
        if (null != requestData.getUserid()) {
            user = systemService.getUser(requestData.getUserid());
        }
        return user;
    }

    /**
     * 把查询出的page中的数据，重新整理到map中并返回
     *
     * @return
     */
    protected Map<String, Object> resetPage(Page page) {
        Map<String,Object> resultMap=new HashMap<String,Object>();
        resultMap.put("pageSize", page.getPageSize());
        resultMap.put("pageNo", page.getPageNo());
        resultMap.put("totalPage", page.getTotalPage());
        resultMap.put("count", page.getCount());
        resultMap.put("list", page.getList());
        return resultMap;
    }

}
